/** @format */

const express = require("express");
const https = require("https");
const http = require("http");
const fs = require("fs");
const path = require("path");
const router = require("./router/index");
const cors = require("cors");
const app = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.static("public"));
app.use("/api", router);

app.use((req, res, next) => {
  // console.log(res);
  res.json({ code: res.statusCode || 400, data: res.data || {}, msg: res.msg || "出错了！！" });
});

// 没有匹配到的路由 客户端错误
app.use((req, res, next) => {
  res.status(404).send("404 NOT FOUND");
});

// 服务器错误
app.use((err, req, res, next) => {
  console.log(err);
  res.status(500).send("SERVICE ERROR");
});

// let certificate = fs.readFileSync(path.join(__dirname, "./key/xxx.pem"), "utf8");
// let privateKey = fs.readFileSync(path.join(__dirname, "./key/xxx.key"), "utf8");
// let credentials = { key: privateKey, cert: certificate };

// const httpsServer = https.createServer(credentials, app);
const httpServer = http.createServer(app);

// httpsServer.listen(3333, () => {
//   console.log("listen on https://127.0.0.1:3333");
// });
httpServer.listen(3334, () => {
  console.log("listen on http://127.0.0.1:3334");
});

// app.listen(3333, () => {
//   console.log("listen on http://127.0.0.1:3333");
// });
